﻿using System;
using System.Threading;

namespace TetrisGame
{
    internal enum E_DifficultyLevel
    {
        Easy = 500, // 简单
        Medium = 300,   // 中等
        Hard = 150,     // 困难
        Crazy = 50 // 疯狂
    }

    internal class GameScene : IUpdateScene
    {
        private readonly Map map;
        private readonly BlockHandler blockHandler; // 方块处理器
        private readonly Thread fallThread; // 用于方块下落的线程
        private readonly E_DifficultyLevel difficultyLevel; // 游戏难度级别
        private static bool isRuning = true; // 游戏是否正在运行

        public GameScene(E_DifficultyLevel difficultyLevel)
        {
            isRuning = true; // 初始化游戏状态为运行中
            this.difficultyLevel = difficultyLevel; // 设置游戏难度级别
            map = new Map(this);
            blockHandler = new BlockHandler();
            fallThread = new Thread(CheckInputThread)
            {
                IsBackground = true
            };
            fallThread.Start();
        }

        public void Update()
        {
            lock (blockHandler)
            {
                map.Draw();
                blockHandler.Draw();
                if (blockHandler.CanMoveBlockCheck(E_MoveDirection.Down, map)) // 检查是否可以向下移动
                    blockHandler.MoveBlock(E_MoveDirection.Down); // 向下移动方块
            }

            Thread.Sleep((int)difficultyLevel);
        }

        /// <summary>
        /// 向下移动方块
        /// </summary>
        private void CheckInputThread()
        {
            while (isRuning)
            {
                if (Console.KeyAvailable)
                {
                    lock (blockHandler)
                    {
                        HandleInput();
                    }
                }
            }
        }

        public void Stop()
        {
            isRuning = false; // 停止游戏
            fallThread.Abort(); // 终止方块下落线程
        }

        private void HandleInput()
        {
            switch (Console.ReadKey(true).Key)
            {
                case ConsoleKey.UpArrow:
                    // 旋转方块
                    if (blockHandler.CanChangeBlockCheck(map)) // 检查是否可以旋转方块
                        blockHandler.ChangeBlockRotation(); // 旋转方块
                    break;

                case ConsoleKey.LeftArrow:
                    if (blockHandler.CanMoveBlockCheck(E_MoveDirection.Left, map)) // 检查是否可以向左移动
                        blockHandler.MoveBlock(E_MoveDirection.Left); // 向左移动方块
                    break;

                case ConsoleKey.RightArrow:
                    if (blockHandler.CanMoveBlockCheck(E_MoveDirection.Right, map)) // 检查是否可以向右移动
                        blockHandler.MoveBlock(E_MoveDirection.Right);
                    break;

                case ConsoleKey.DownArrow:
                    if (blockHandler.CanMoveBlockCheck(E_MoveDirection.Down, map)) // 检查是否可以向下移动
                        blockHandler.MoveBlock(E_MoveDirection.Down); // 向下移动方块
                    break;
            }
        }
    }
}